// next作为koa中间件使用

const koa = require("koa");
const session = require("koa-session");
const Router = require("koa-router");
const RedisSessionStore = require("./server/session-store");
const Redis = require("ioredis");
const redis = new Redis();

const auth = require("./server/auth");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handler = app.getRequestHandler();

app.prepare().then(() => {
  const server = new koa();
  const router = new Router();

  router.get("/api/user/info", async (ctx) => {
    const user = ctx.session?.userInfo;

    if (!user) {
      ctx.status = 401;
      ctx.body = "Need Login";
    } else {
      ctx.body = user;
      ctx.set("Content-Type", "application/json");
    }
  });
  server.use(router.routes());

  server.use(async (ctx) => {
    ctx.req.session = ctx.session;
    await handler(ctx.req, ctx.res);
    ctx.respond = false;
  });

  auth(server);

  server.listen(3000);
});
